package nl.maarten.docenthelp.entity.thread;

import java.net.DatagramPacket;
import java.net.InetAddress;

import nl.maarten.docenthelp.entity.Session;
import nl.maarten.docenthelp.manager.SessionManager;


public class ListenThread extends Thread
{
	private boolean running = false;
	
	private SessionManager sessionManager = SessionManager.getInstance();
	
	private DatagramPacket packet;
	
	private byte[] receiveData = new byte[1024];
	
	public void run()
	{
		running = true;
		
		while( running )
		{
			for( Session session : sessionManager.getSessions().values() )
			{
				packet = new DatagramPacket(receiveData, receiveData.length);
				try
				{
					session.getUdpSocket().receive(packet);
					System.out.println( new String( packet.getData() ) );
					int port = packet.getPort();
					InetAddress address = packet.getAddress();
					if( session.getUdpPort() != port )
					{
						session.setUdpPort( port );
						session.setUdpAddress( address );
						session.sendMessage( "Bedankt voor uw poort!" );
					}
				}
				catch( Exception e )
				{
					e.printStackTrace();
				}
			}
		}
	}
	
	public void close()
	{
		running = false;
		
		try
		{
			this.join();
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
	}
}
